﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommandLib
{
    /// <summary>
    /// 二进制文件读写类
    /// </summary>
    public class OperateDat
    {
        /// <summary>
        /// 二进制文件写入
        /// </summary>
        /// <param name="filepath">文件路径</param>
        /// <param name="context">内容</param>
        public static void WriteDAT(String filepath, String context)
        {
            FileStream stream = null;
            BinaryWriter bwrite = null;
            try
            {
                if (!File.Exists(filepath))
                {
                   
                    String dir = Path.GetDirectoryName(filepath);
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }

                }
                stream = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                bwrite = new BinaryWriter(stream);
                bwrite.Write(context);

            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                bwrite.Close();
                stream.Close();
            }

        }
        /// <summary>
        /// 二进制文件读取
        /// </summary>
        /// <param name="filepath">路径</param>
        /// <returns></returns>
        public static String ReadDAT(String filepath)
        {

            String result = null;
            try
            {
                using (FileStream stream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
                {
                    using (BinaryReader biread = new BinaryReader(stream))
                    {
                        if (biread.PeekChar() != -1)
                        {
                            result = biread.ReadString();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return result;
        }
    }
}
